import * as echarts from '../../../components/ec-canvas/echarts'
const util = require('../../../../utils/util.js')
const app = getApp()
let comprehensiveChart = null
let achievementChart = null
let trainingChart = null
let vitalChart = null
let interviewChart = null
import option from './option'
let comprehensiveAnalysisOption = option.comprehensiveAnalysis
let achievementStatisticsOption = option.achievementStatistics
let trainingStatisticsOption = option.trainingStatistics
let vitalStatisticsOption = option.vitalStatistics
let interviewStatisticsOption = option.interviewStatistics
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startdate: (util.timestampToTime(Date.now() - 7 * 60 * 60 * 24 * 1000)),
    enddate: (util.timestampToTime(Date.now() - 0 * 60 * 60 * 24 * 1000)),
    navBarHeight: app.globalData.navBarHeight,
    CDNPATH: app.globalData.CDNPATH,
    info: '',
    bankList: [],
    radarImg: '',
    bankidList: [],
    bankindex: '',
    branchList: [],
    branchidList: [],
    branchidindex: '',
    subBranchList: [],
    subBranchidList: [],
    subBranchindex: '',
    siteList: [],
    siteidList: [],
    siteindex: '',
    selectlist: [{name: '银行', num: 500, active: false}, {name: '分行', num: 500, active: false}, {name: '支行', num: 10000, active: false}, {name: '网点', num: 10000, active: false}],
    tablist: [{name: '登录数', num: 500, active: true}, {name: '添加客户数', num: 500, active: false}, {name: '生成计划书', num: 10000, active: false}, {name: '约访练习次数', num: 9000, active: false}, {name: '面谈练习次数', num: 9000, active: false}, {name: '计划书浏览数', num: 10000, active: false}],
    queryForm: { bankId: '', bankBranchId: '', bankSubBranchId: '', bankWorkstationId: '', startDate: '', endDate: '' },
    query: { bankName: '', bankBranchName: '', bankSubBranchName: '', bankWorkstationName: '' },
    params: { parentId: ''},
    gradeStat: [],
    sparringNumStat: [],
    appointmentNumStat: [],
    interviewNumStat: [],
    ecComprehensive: {
      onInit: function (canvas, width, height, dpr) {
        comprehensiveChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(comprehensiveChart);
        comprehensiveChart.setOption(comprehensiveAnalysisOption);
        return comprehensiveChart;
      }
    },
    ecAchievement: {
      onInit: function (canvas, width, height, dpr) {
        achievementChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(achievementChart);
        achievementChart.setOption(achievementStatisticsOption);
        return achievementChart;
      }
    },
    ecTrainall: {
      onInit: function (canvas, width, height, dpr) {
        trainingChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(trainingChart);
        trainingChart.setOption(trainingStatisticsOption);
        return trainingChart;
      }
    },
    ecTrainone: {
      onInit: function (canvas, width, height, dpr) {
        vitalChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(vitalChart);
        vitalChart.setOption(vitalStatisticsOption);
        return vitalChart;
      }
    },
    ecTraintwo: {
      onInit: function (canvas, width, height, dpr) {
        interviewChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(interviewChart);
        interviewChart.setOption(interviewStatisticsOption);
        return interviewChart;
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 安卓
    wx.setBackgroundColor({
      backgroundColor: '#0061E3',
    })
    // 兼容ios
    wx.setBackgroundColor({
      backgroundColorTop: '#0061E3',
      backgroundColorBottom: '#F3F6FA',
    })  
    this.data.queryForm.startDate = (util.timestampToTime(Date.now() - 7 * 60 * 60 * 24 * 1000))
    this.data.queryForm.endDate = (util.timestampToTime(Date.now() - 0 * 60 * 60 * 24 * 1000))
    this.setData({
      queryForm: this.data.queryForm
    })
    var value = JSON.parse(wx.getStorageSync('userInfo'))
    this.setData({
      info: value
    })
    // this.getcurrentOrgDetail()
    this.getAllBankList()
    this.getsparringAnalysis()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getcurrentOrgDetail () {
    app.api.get({
      url: 'cpic_org_getOrgLevel',
      data: { id: app.globalData.userInfo.orgId }
    }).then(res => {
      this.data.query.bankName = res.bank.id === app.globalData.userInfo.orgId ? '' : res.bank.orgName
      this.data.queryForm.bankId = res.bank ? res.bank.id : ''
      this.data.bankindex = res.bank.id === app.globalData.userInfo.orgId ? 0 : ''

      this.data.query.bankBranchName = (res.branch && res.branch.id) === app.globalData.userInfo.orgId ? '' : (res.branch && res.branch.orgName)
      this.data.queryForm.bankBranchId = res.branch ? res.branch.id : ''
      this.data.branchidindex = (res.branch && res.branch.id) === app.globalData.userInfo.orgId ? 0 : ''
      
      this.data.query.bankSubBranchName = (res.subBranch && res.subBranch.id) === app.globalData.userInfo.orgId ? '' : (res.subBranch && res.subBranch.orgName)
      this.data.queryForm.bankSubBranchId = res.subBranch ? res.subBranch.id : ''
      this.data.subBranchindex = (res.subBranch && res.subBranch.id) === app.globalData.userInfo.orgId ? 0 : ''

      this.data.query.bankWorkstationName = res.site ? '' : ''
      this.data.queryForm.bankWorkstationId = res.site ? res.site.id : ''
      this.data.siteindex = res.site ? 0 : ''
      this.setData({
        query: this.data.query,
        queryForm: this.data.queryForm,
        bankindex: this.data.bankindex,
        branchidindex: this.data.branchidindex,
        subBranchindex: this.data.subBranchindex,
        siteindex: this.data.siteindex
      })
    })
  },
  // 获取所有银行
  getAllBankList () {
    app.api.post({
      url: 'userAccessableBank_getAccessableBank',
      data: {}
    }).then(res => {
      // 银行

      if (res.length > 0) {
        res.map(item => {
          this.data.bankList.push(item.orgName)
          this.data.bankidList.push(item.id)
        })
      }
      this.setData({
        bankList: this.data.bankList,
        bankidList: this.data.bankidList,
      })
    })
  },
  bankChange: function(e) {
    this.data.queryForm.bankId = this.data.bankidList[e.detail.value]
    this.data.params.parentId = this.data.bankidList[e.detail.value]
    this.setData({
      bankindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.branchList = []
        this.data.branchidList = []
        res.map(item => {
            this.data.branchList.push(item.orgName)
            this.data.branchidList.push(item.id)
          })
      } else {
        this.data.branchList = []
        this.data.subBranchList = []
        this.data.siteList = []
      }
      this.data.queryForm.bankBranchId = ''
      this.data.queryForm.bankSubBranchId = ''
      this.data.queryForm.bankWorkstationId = ''
      this.setData({
        branchList: this.data.branchList,
        subBranchList: this.data.subBranchList,
        siteList: this.data.siteList,
        branchidList: this.data.branchidList,
        branchidindex: '',
        subBranchindex: '',
        siteindex: '',
        queryForm: this.data.queryForm
      }, () => {
        this.getsparringAnalysis()
      })
    })
  },
  bankCancel: function () {
    this.data.queryForm.bankId = ''
    this.data.queryForm.bankBranchId = ''
    this.data.queryForm.bankSubBranchId = ''
    this.data.queryForm.bankWorkstationId = ''
    this.data.branchList = []
    this.data.subBranchList = []
    this.data.siteList = []
    this.setData({
      bankindex: '',
      branchidindex: '',
      subBranchindex: '',
      siteindex: '',
      queryForm: this.data.queryForm,
      branchList: this.data.branchList,
      subBranchList: this.data.subBranchList,
      siteList: this.data.siteList
    })
    this.getsparringAnalysis()
  },
  branchChange: function(e) {
    this.data.queryForm.bankBranchId = this.data.branchidList[e.detail.value]
    this.data.params.parentId = this.data.branchidList[e.detail.value]
    this.setData({
      branchidindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      console.log(res)
      if (res.length > 0) {
        this.data.subBranchList = []
        this.data.subBranchidList = []
        res.map(item => {
            this.data.subBranchList.push(item.orgName)
            this.data.subBranchidList.push(item.id)
          })
      } else {
        this.data.subBranchList = []
        this.data.siteList = []
      }
      this.data.queryForm.bankSubBranchId = ''
      this.data.queryForm.bankWorkstationId = ''
      this.setData({
        subBranchList: this.data.subBranchList,
        siteList: this.data.siteList,
        queryForm: this.data.queryForm,
        subBranchindex: '',
        siteindex: '',
        subBranchidList: this.data.subBranchidList
      }, () => {
        this.getsparringAnalysis()
      })
    })
  },
  branchCancel: function() {
    this.data.queryForm.bankBranchId = ''
    this.data.queryForm.bankSubBranchId = ''
    this.data.queryForm.bankWorkstationId = ''
    this.data.subBranchList = []
    this.data.siteList = []
    this.setData({
      branchidindex: '',
      subBranchindex: '',
      siteindex: '',
      queryForm: this.data.queryForm,
      subBranchList: this.data.subBranchList,
      siteList: this.data.siteList
    })
    this.getsparringAnalysis()
  },
  subBranchChange: function(e) {
    console.log(e, this.data.subBranchList)
    this.data.queryForm.bankSubBranchId = this.data.subBranchidList[e.detail.value]
    this.data.params.parentId = this.data.subBranchidList[e.detail.value]
    this.setData({
      subBranchindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.siteList = []
        this.data.siteidList = []
        res.map(item => {
            this.data.siteList.push(item.orgName)
            this.data.siteidList.push(item.id)
          })
      } else {
        this.data.siteList = []
      }
      this.data.queryForm.bankWorkstationId = ''
      this.setData({
        siteList: this.data.siteList,
        queryForm: this.data.queryForm,
        siteindex: '',
        siteidList: this.data.siteidList
      }, () => {
        this.getsparringAnalysis()
      })
    })
  },
  subBranchCancel: function() {
    this.data.queryForm.bankSubBranchId = ''
    this.data.queryForm.bankWorkstationId = ''
    this.data.siteList = []
    this.setData({
      subBranchindex: '',
      siteindex: '',
      queryForm: this.data.queryForm,
      siteList: this.data.siteList
    })
    this.getsparringAnalysis()
  },
  siteChange: function(e) {
    this.data.queryForm.bankWorkstationId = this.data.siteidList[e.detail.value]
    this.setData({
      siteindex: e.detail.value,
      queryForm: this.data.queryForm
    })
    this.getsparringAnalysis()
  },
  siteCancel: function() {
    this.data.queryForm.bankWorkstationId = ''
    this.setData({
      siteindex: '',
      queryForm: this.data.queryForm
    })
    this.getsparringAnalysis()
  },
  // 开始时间
  bindstartDateChange: function(e) {
    this.setData({
      startdate: e.detail.value
    })
    this.data.queryForm.startDate = e.detail.value
    this.setData({
      queryForm: this.data.queryForm
    })
    this.getsparringAnalysis()
  },
  // 结束时间
  bindendDateChange: function(e) {
    this.setData({
      enddate: e.detail.value
    })
    this.data.queryForm.endDate = e.detail.value
    this.setData({
      queryForm: this.data.queryForm
    })
    this.getsparringAnalysis()
  },
  getsparringAnalysis () {
    app.api.post({
      url: 'report_sparring_sparringAnalysis',
      data: this.data.queryForm
    }).then(res => {
      // 综合分析
      let Data = []
      if (res.comprehensiveAnalysis.length > 0) {
        res.comprehensiveAnalysis.map(item => {
          Data.push(item.score)
        })
      }
      comprehensiveAnalysisOption.series[0].data[0].value = Data
      if (comprehensiveChart) {
        comprehensiveChart.clear()
        comprehensiveChart.setOption(comprehensiveAnalysisOption, true)
      }
      // 成绩统计
      let data = []
      let color = ['#266ABE', '#3AA0FF', '#43C9C3', '#907FFF']
      if (res.gradeStat.length > 0) {
        res.gradeStat.map((v, k) => {
          v.color = color[k]
        })
        this.data.gradeStat = res.gradeStat
        console.log(this.data.gradeStat)
        this.setData({
          gradeStat: this.data.gradeStat
        })
        res.gradeStat.map((v, k) => {
          // const name = `${v.name}${v.ratio}% （${v.num}次）`
          data.push(v.num ? v.num : null)
        })
      }
      if (res.gradeStat.length === 0) {
        this.setData({
          gradeStat: []
        })
      }
      achievementStatisticsOption.series[0].data = data
      achievementStatisticsOption.series[0].label.formatter = (params) => {
        return '{score|' + res.avgGrade + '}\n{title|平均分数}'
      }
      if (achievementChart) {
        achievementChart.clear()
        achievementChart.setOption(achievementStatisticsOption, true)
      }
      // 陪练统计
      let data1 = []
      let color1 = ['#3AA0FF', '#43C9C3']
      if (res.sparringNumStat.length > 0) {
        res.sparringNumStat.map((v, k) => {
          v.color = color1[k]
        })
        this.data.sparringNumStat = res.sparringNumStat
        this.setData({
          sparringNumStat: this.data.sparringNumStat
        })
        res.sparringNumStat.map((v, k) => {
          // const name = `${v.name}${v.ratio}% （${v.num}次）`
          data1.push(v.num ? v.num : null)
        })
      }
      if (res.sparringNumStat.length === 0) {
        this.setData({
          sparringNumStat: []
        })
      }
      
      trainingStatisticsOption.series[0].data = data1
      trainingStatisticsOption.series[0].label.formatter = (params) => {
        return '{score|' + res.sparringTotalNum + '}\n{title|总次数}'
      }
      if (trainingChart) {
        trainingChart.clear()
        trainingChart.setOption(trainingStatisticsOption, true)
      }
      // 约访统计
      let data2 = []
      let color2 = ['#4781C8', '#58AFFF', '#60D2CC', '#907FFF', '#F19C9C']
      if (res.appointmentNumStat.length > 0) {
        res.appointmentNumStat.map((v, k) => {
          v.color = color2[k]
        })
        this.data.appointmentNumStat = res.appointmentNumStat
      this.setData({
        appointmentNumStat: this.data.appointmentNumStat
      })
      res.appointmentNumStat.map((v, k) => {
        // const name = `${v.name}${v.ratio}% （${v.num}次）`
        data2.push(v.num ? v.num : null)
      })
      }
      if (res.appointmentNumStat.length === 0) {
        this.setData({
          appointmentNumStat: []
        })
      }
      vitalStatisticsOption.series[0].data = data2
      vitalStatisticsOption.series[0].label.formatter = (params) => {
        return '{score|' + res.appointmentTotalNum + '}\n{title|总次数}'
      }
      if (vitalChart) {
        vitalChart.clear()
        vitalChart.setOption(vitalStatisticsOption, true)
      }
      // 面谈占比
      let data3 = []
      let color3 = ['#4781C8', '#58AFFF', '#60D2CC', '#907FFF', '#F19C9C']
      if (res.interviewNumStat.length > 0) {
        res.interviewNumStat.map((v, k) => {
          v.color = color3[k]
        })
        this.data.interviewNumStat = res.interviewNumStat
        this.setData({
          interviewNumStat: this.data.interviewNumStat
        })
        res.interviewNumStat.map((v, k) => {
          // const name = `${v.name}${v.ratio}% （${v.num}次）`
          data3.push(v.num ? v.num : null)
        })
      }
      if (res.interviewNumStat.length === 0) {
        this.setData({
          interviewNumStat: []
        })
      }
      interviewStatisticsOption.series[0].data = data3
      interviewStatisticsOption.series[0].label.formatter = (params) => {
        return '{score|' + res.interviewTotalNum + '}\n{title|总次数}'
      }
      if (interviewChart) {
        interviewChart.clear()
        interviewChart.setOption(interviewStatisticsOption, true)
      }
    })
  }
})